﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace Gollie.Pdf
{
	public class PdfDocumentCanvas : IDisposable
	{
		private PdfContentByte canvas = null;
		private PdfReader reader = null;
		private PdfWriter writer = null;
		private PdfStamper stamper = null;
		private Document doc = null;
		private FileStream fs = null;

		public PdfDocumentCanvas(string targetPath)
			: this(targetPath, null)
		{
		}

		public PdfDocumentCanvas(string targetPath, string templatePath)
		{
			fs = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None);

			if (templatePath != null)
			{
				reader = new PdfReader(templatePath);

				stamper = new PdfStamper(reader, fs);
				stamper.SetFullCompression();
				canvas = stamper.GetOverContent(1);
			}
			else
			{
				doc = new Document();
				writer = PdfWriter.GetInstance(doc, fs);

				canvas = writer.DirectContent;
			}
		}

		public void WriteTable(PdfTable table)
		{
			table.WriteSelectedRows(0, -1, table.Properties.X, table.Properties.Y, canvas);
		}

		public void Dispose()
		{
			Dispose(true);

			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (doc != null) doc.Close();
				if (writer != null) writer.Close();
				if (stamper != null) stamper.Close();
				if (reader != null) reader.Close();
				if (fs != null) fs.Close();
			}
		}
	}
}
